//
//  TFPhotoBrowserViewController.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/11/22.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPhotoBrowserViewController.h"
//UI
#import "TFPhotoBrowserDisplayCell.h"
#import "TFPhotoBrowserVideoDisplayCell.h"
#import "TFPhotoBrowserNavigationBar.h"
//工具
#import "TFPhotoBrowserPresentTransition.h"
#import "TFPhotoResourceHelper.h"
#import "UIImage+TFPhoto.h"
#import <Photos/PHAsset.h>

@interface TFPhotoBrowserViewController ()<UIViewControllerTransitioningDelegate,TFPhotoBrowserPresentTransitionDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *percentDrivenTransition;

@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong, readwrite) UIView *bottomView;

@property (nonatomic, strong, readwrite) TFPhotoBrowserNavigationBar *navigationBar;

@property (nonatomic, strong, readwrite) UINavigationItem *topNavigationItem;

@property (nonatomic, strong, readwrite) UICollectionView *collectionView;

@property (nonatomic, weak) UIImageView *placeholderImageView;

@end

@implementation TFPhotoBrowserViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.navigationBar];
    
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewControllerCustomBottomView:)]) {
        self.bottomView = [self.delegate photoBrowserViewControllerCustomBottomView:self];
    }
    else {
        self.bottomView = [self getDefaultBottomView];
        if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didCreatedBottomBar:)]) {
            [self.delegate photoBrowserViewController:self didCreatedBottomBar:(UIToolbar *)self.bottomView];
        }
    }
    [self.view addSubview:self.bottomView];
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:customConstraintsWithSubView:collectionView:bottomView:)]) {
        [self.delegate photoBrowserViewController:self customConstraintsWithSubView:self.navigationBar collectionView:self.collectionView bottomView:self.bottomView];
    }
    else {
        //添加约束
        [self addConstraintsForSubViews];
    }
    
    
    
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewControllerViewDidLoad:)]) {
        [self.delegate photoBrowserViewControllerViewDidLoad:self];
    }
    [self p_setNavigationBarAndBottomViewHidden:YES withAnimated:NO];
    
    //添加手势
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(p_didDoubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.delegate = self;
    [self.view addGestureRecognizer:doubleTap];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(p_didSingleTap:)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.delegate = self;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.view addGestureRecognizer:singleTap];
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(p_panGestureAction:)];
    panGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:panGestureRecognizer];
    
    [self reload];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self p_setNavigationBarAndBottomViewHidden:NO withAnimated:YES];
    TFPhotoBrowserDisplayCell *cell = (TFPhotoBrowserDisplayCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
    cell.hidden = NO;
    if (!cell.photoScrollView.image) {
        cell.photoScrollView.image = _placeholderImageView.image;
    }
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didDisplayCell:)]) {
        [self.delegate photoBrowserViewController:self didDisplayCell:self.currentDisplayCell];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.collectionView layoutIfNeeded];
    [self.collectionView setContentOffset:CGPointMake(_currentPage*CGRectGetWidth(self.collectionView.frame), 0) animated:NO];
}

#pragma mark - public

- (void)reload {
    self.totalPage = [self.dataSource numberOfPhotosInPhotoBrowserViewController:self];
    if (self.currentPage>self.totalPage-1) {
        self.currentPage = self.totalPage - 1;
    }
    [self p_updateNavigationBarTitle];
    [self.collectionView reloadData];
}

- (Class)photoBrowserCellClass {
    if ([self.dataSource respondsToSelector:@selector(photoBrowserViewControllerCellClassForDisplay:)]) {
        return [self.dataSource photoBrowserViewControllerCellClassForDisplay:self];
    }
    return [TFPhotoBrowserDisplayCell class];
}

- (Class)photoBrowserVideoCellClass {
    if ([self.dataSource respondsToSelector:@selector(photoBrowserViewControllerVideoCellClassForDisplay:)]) {
        return [self.dataSource photoBrowserViewControllerVideoCellClassForDisplay:self];
    }
    return [TFPhotoBrowserVideoDisplayCell class];
}

- (void)addConstraintsForSubViews {
    //添加约束
    _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    _navigationBar.translatesAutoresizingMaskIntoConstraints = NO;
    _bottomView.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSDictionary *viewDic = @{@"navigationBar":self.navigationBar,@"bottomView":self.bottomView,@"collectionView":self.collectionView};
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[collectionView]|" options:0 metrics:nil views:viewDic]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[collectionView]|" options:0 metrics:nil views:viewDic]];
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[navigationBar]|" options:0 metrics:nil views:viewDic]];
    [NSLayoutConstraint constraintWithItem:self.navigationBar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:self.navigationBar attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:64.0].active = YES;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bottomView]|" options:0 metrics:nil views:viewDic]];
    [NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:CGRectGetHeight(_bottomView.frame)?:49.0].active = YES;
}

- (UIToolbar *)getDefaultBottomView {
    UIToolbar *bottomBar = [[UIToolbar alloc] init];
    bottomBar.barStyle = UIBarStyleBlack;
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(p_bottomBarShareAction)];
    shareItem.tintColor = [UIColor whiteColor];
    UIBarButtonItem *fixItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [bottomBar setItems:@[fixItem,shareItem]];
    return bottomBar;
}

- (NSInteger)indexForCell:(UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell {
    return [self.collectionView indexPathForCell:cell].row;
}

- (UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)displayCellAtIndex:(NSInteger)index {
    return (UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}

- (UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)currentDisplayCell {
    return [self displayCellAtIndex:_currentPage];
}

#pragma mark - privite

- (void)p_updateNavigationBarTitle {
    self.topNavigationItem.title = [NSString stringWithFormat:@"%zd/%zd",self.currentPage+1,self.totalPage];
}

#pragma mark - view actions.

- (void)p_navigationItemBackAction {
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewControllerWillDismiss:)]) {
        [self.delegate photoBrowserViewControllerWillDismiss:self];
    }
    typeof(self) __weak weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        if ([weakSelf.delegate respondsToSelector:@selector(photoBrowserViewControllerDidDismiss:)]) {
            [weakSelf.delegate photoBrowserViewControllerDidDismiss:weakSelf];
        }
    }];
}

- (void)p_bottomBarShareAction {
    UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *displayCell = (UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
    if (displayCell.image) {
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[displayCell.image] applicationActivities:nil];
        [self presentViewController:activityVC animated:YES completion:nil];
    }
    else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"提示"] message:[TFPhotoResourceHelper localizedStringWithKey:@"图片加载完成之后才可以分享"] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"确定"] style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:confirmAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)p_didSingleTap:(UITapGestureRecognizer *)tap {
    BOOL hidden = (self.navigationBar.alpha==0);
    hidden = !hidden;
    [self p_setNavigationBarAndBottomViewHidden:hidden withAnimated:YES];
}

- (void)p_setNavigationBarAndBottomViewHidden:(BOOL)hidden withAnimated:(BOOL)animated {
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            [self setBarsHidden:hidden];
        }];
    }
    else {
        [self setBarsHidden:hidden];
    }
}

- (void)setBarsHidden:(BOOL)hidden {
    if (hidden) {
        self.navigationBar.transform = CGAffineTransformMakeTranslation(0, -CGRectGetHeight(self.navigationBar.frame));
        self.bottomView.transform = CGAffineTransformMakeTranslation(0, CGRectGetHeight(self.bottomView.frame)+1);
        self.navigationBar.alpha = 0.0;
        self.bottomView.alpha = 0.0;
    }
    else {
        self.navigationBar.transform = CGAffineTransformIdentity;
        self.bottomView.transform = CGAffineTransformIdentity;
        self.navigationBar.alpha = 1.0;
        self.bottomView.alpha = 1.0;
    }
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:navigationBarAndBottomBarDoMoveAnimationWithHidden:)]) {
        [self.delegate photoBrowserViewController:self navigationBarAndBottomBarDoMoveAnimationWithHidden:hidden];
    }
}

- (void)p_didDoubleTap:(UITapGestureRecognizer *)tap {
    TFPhotoBrowserDisplayCell *cell = (TFPhotoBrowserDisplayCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
    if (cell.photoScrollView.zoomImageView.image) {
        if (cell.photoScrollView.zoomScale >= 1.0) {
            [cell.photoScrollView setZoomScale:cell.photoScrollView.minimumZoomScale animated:YES];
        }
        else {
            [cell.photoScrollView setZoomScale:cell.photoScrollView.maximumZoomScale animated:YES];
        }
    }
    return;
    
    
}

-(void)p_panGestureAction:(UIPanGestureRecognizer *)recognizer{
    CGFloat translationY = [recognizer translationInView:self.view].y;
    CGFloat translationX = [recognizer translationInView:self.view].x;
    CGPoint velocity = [recognizer velocityInView:self.view];
    CGFloat progress = 1 - fabs(translationY)/(CGRectGetHeight(self.view.frame)/2);
    progress = MAX(progress, 0.0);
    CGFloat scale = MAX(progress, 0.5);
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        _percentDrivenTransition = [[UIPercentDrivenInteractiveTransition alloc] init];
        [self p_navigationItemBackAction];
    }else if (recognizer.state == UIGestureRecognizerStateChanged){
        CGAffineTransform translationTransform = CGAffineTransformMakeTranslation(translationX/scale, translationY/scale);
        CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scale, scale);
        _placeholderImageView.transform = CGAffineTransformConcat(translationTransform, scaleTransform);
        [self.percentDrivenTransition updateInteractiveTransition:progress];
    }
    
    if (recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateEnded){
        if (fabs(translationY) > 100 || fabs(velocity.y) > 500) {
            [_percentDrivenTransition finishInteractiveTransition];
        }
        else {
            [_percentDrivenTransition cancelInteractiveTransition];
        }
        _percentDrivenTransition = nil;
    }
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    TFPhotoBrowserPresentTransition *transition = [[TFPhotoBrowserPresentTransition alloc] init];
    transition.delegate = self;
    return transition;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    TFPhotoBrowserPresentTransition *transition = [[TFPhotoBrowserPresentTransition alloc] init];
    transition.delegate = self;
    return transition;
}


- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator {
    
    return _percentDrivenTransition;
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint locationPoint = [gestureRecognizer locationInView:self.view];
    if (CGRectContainsPoint(_navigationBar.frame, locationPoint)||CGRectContainsPoint(_bottomView.frame, locationPoint)) {
        return NO;
    }
    return YES;
}

#pragma mark - TFPhotoBrowserPresentTransitionDelegate

- (void)photoBrowserPresentTransitionAnimateTransition:(id<UIViewControllerContextTransitioning>)transitionContext duration:(NSTimeInterval)duration{
    if (self.isBeingDismissed|self.isBeingPresented) {
        UIView *containerView = [transitionContext containerView];
        //获取图片view对应的from和to两个状态的值
        UIView *fromView = nil;
        CGRect fromFrame = CGRectZero;
        UIImage *fromImage = nil;
        if ([self.dataSource respondsToSelector:@selector(photoBrowserViewController:originalPhotoViewAtIndex:)]) {
            TFPhotoBrowserOriginalPhotoViewModel *originalViewModel = [self.dataSource photoBrowserViewController:self originalPhotoViewAtIndex:self.currentPage];
            fromView = originalViewModel.originalPhotoView;
            fromImage = originalViewModel.originalImage;
            fromFrame = [fromView.superview convertRect:fromView.frame toView:self.view];
        }
        if (!fromView) {
            fromFrame.origin = self.view.center;
        }
        TFPhotoBrowserDisplayCell *cell = nil;
        if (self.isBeingPresented) {
            cell = [[TFPhotoBrowserDisplayCell alloc] initWithFrame:self.view.bounds];
            [cell setPhoto:[self.dataSource photoBrowserViewController:self photoForIndex:self.currentPage]];
            [cell loadPhoto];
        }
        else {
            cell = (TFPhotoBrowserDisplayCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
        }
        
        UIImageView *toImageView = cell.photoScrollView.zoomImageView;
        
        if (!toImageView.image&&fromImage) {
            //先显示缩略图
            cell.photoScrollView.image = fromImage;
        }
        CGRect toFrame = cell.photoScrollView.zoomImageView.frame;
        
        UIImageView *placeholderImageView = nil;
        if (toImageView.image) {
            placeholderImageView = [[UIImageView alloc] initWithImage:[toImageView.image tfPhoto_fixedOrientationImage]];
            placeholderImageView.clipsToBounds = YES;
            placeholderImageView.contentMode = UIViewContentModeScaleAspectFill;
        }
        if (placeholderImageView) {
            [containerView addSubview:placeholderImageView];
        }
        _placeholderImageView = placeholderImageView;
        if (self.isBeingPresented) {
            fromView.alpha = 0.0;
            placeholderImageView.frame = fromFrame;
            [containerView insertSubview:self.view atIndex:0];
            
            //设置view动画的初始状态
            self.view.frame = containerView.bounds;
            self.view.alpha = 0.0;
            [UIView animateWithDuration:duration animations:^{
                self.view.backgroundColor = [UIColor blackColor];
                self.view.alpha = 1.0;
                placeholderImageView.frame = toFrame;
            } completion:^(BOOL finished) {
                BOOL complete = [transitionContext transitionWasCancelled];
                [UIView animateWithDuration:0.3 animations:^{
                    fromView.alpha = 1.0;
                    [placeholderImageView removeFromSuperview];
                }];
                [transitionContext completeTransition:!complete];
            }];
        }
        else if (self.isBeingDismissed) {
            placeholderImageView.frame = toFrame;
            fromView.alpha = 0.0;
            toImageView.alpha = 0.0;
            [UIView animateWithDuration:duration animations:^{
                self.view.alpha = 0.0;
                if (!_percentDrivenTransition) {
                    placeholderImageView.frame = fromFrame;
                }
            } completion:^(BOOL finished) {
                BOOL complete = [transitionContext transitionWasCancelled];
                
                [UIView animateWithDuration:0.3 animations:^{
                    toImageView.alpha = 1.0;
                    fromView.alpha = 1.0;
                    self.view.alpha = 1.0;
                    [placeholderImageView removeFromSuperview];
                }];
                [transitionContext completeTransition:!complete];
            }];
        }
    }
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _totalPage;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    id photo = [self.dataSource photoBrowserViewController:self photoForIndex:indexPath.row];
    NSTimeInterval duration = 0.0;
    if ([photo isKindOfClass:[PHAsset class]]) {
        duration = ((PHAsset *)photo).duration;
    }
    Class cellClass = nil;
    if (duration) {
        cellClass = [self photoBrowserVideoCellClass];
    }
    else {
        cellClass = [self photoBrowserCellClass];
    }
    UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.photo = [self.dataSource photoBrowserViewController:self photoForIndex:indexPath.row];
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didReloadCell:)]) {
        [self.delegate photoBrowserViewController:self didReloadCell:cell];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    cell.photo = [self.dataSource photoBrowserViewController:self photoForIndex:indexPath.row];
    [cell loadPhoto];
    if (self.navigationBar.alpha != 0.0 && self.view.window) {
        [self p_setNavigationBarAndBottomViewHidden:YES withAnimated:YES];
    }
    if (self.isBeingPresented) {
        cell.hidden = YES;
    }
    else {
        cell.hidden = NO;
    }
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:willDisplayCell:)]) {
        [self.delegate photoBrowserViewController:self willDisplayCell:cell];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [cell clearPhoto];
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didEndDisplayCell:)]) {
        [self.delegate photoBrowserViewController:self didEndDisplayCell:cell];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentPage = (NSInteger)scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame);
    if (currentPage!=self.currentPage) {
        self.currentPage = currentPage;
        if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didDisplayCell:)]) {
            [self.delegate photoBrowserViewController:self didDisplayCell:self.currentDisplayCell];
        }
    }
    [self p_updateNavigationBarTitle];
}

#pragma mark - TFPhotoBrowserDisplayCellDelegate

- (void)photoBrowserDisplayCellDidLoadPhoto:(__kindof UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell {
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:cellDidLoadPhoto:)]) {
        [self.delegate photoBrowserViewController:self cellDidLoadPhoto:cell];
    }
}

- (void)photoBrowserDisplayCellDidFinishLoadPhoto:(__kindof UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell {
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:cellDidFinishLoadPhoto:)]) {
        [self.delegate photoBrowserViewController:self cellDidFinishLoadPhoto:cell];
    }
}

- (void)photoBrowserDisplayCellDidClearPhoto:(__kindof UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell {
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:cellDidClearLoadPhoto:)]) {
        [self.delegate photoBrowserViewController:self cellDidClearLoadPhoto:cell];
    }
}

- (void)photoBrowserDisplayCellDidFinishLoadPhotoFromICloud:(__kindof UICollectionViewCell<TFPhotoBrowserDisplayCellPublic> *)cell {
    if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:cellDidFinishLoadPhotoFromICloud:)]) {
        [self.delegate photoBrowserViewController:self cellDidFinishLoadPhotoFromICloud:cell];
    }
}

#pragma mark - lazy load.

- (BOOL)topNavigationBarHidden {
    return (self.navigationBar.alpha==0);
}

- (UINavigationItem *)topNavigationItem {
    if (!_topNavigationItem) {
        _topNavigationItem = [[UINavigationItem alloc] init];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"返回"] style:UIBarButtonItemStylePlain target:self action:@selector(p_navigationItemBackAction)];
        backItem.tintColor = [UIColor whiteColor];
        _topNavigationItem.leftBarButtonItem = backItem;
    }
    return _topNavigationItem;
}

- (UINavigationBar *)navigationBar {
    if (!_navigationBar) {
        _navigationBar = [[TFPhotoBrowserNavigationBar alloc] init];
        switch (_topNavigationBarBackgroundStyle) {
            case TFPhotoBrowserTopNavigationBarBackgroundStyleBlack:
            {
                _navigationBar.barStyle = UIBarStyleBlack;
                [_navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionTop barMetrics:UIBarMetricsDefault];
            }
                break;
                
            default:
                break;
        }
        [_navigationBar setItems:@[self.topNavigationItem]];
        if ([self.delegate respondsToSelector:@selector(photoBrowserViewController:didCreatedNaivgationBar:)]) {
            [self.delegate photoBrowserViewController:self didCreatedNaivgationBar:_navigationBar];
        }
    }
    return _navigationBar;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(screenSize.width, screenSize.height);
        flowLayout.minimumLineSpacing = 0.0;
        flowLayout.minimumInteritemSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        
        Class cellClass = [self photoBrowserCellClass];
        [_collectionView registerClass:cellClass forCellWithReuseIdentifier:NSStringFromClass(cellClass)];
        Class videoCellClass = [self photoBrowserVideoCellClass];
        [_collectionView registerClass:videoCellClass forCellWithReuseIdentifier:NSStringFromClass(videoCellClass)];
    }
    return _collectionView;
}

- (void)dealloc {
    NSLog(@"\n******************************************\n %s---line:%d \n******************************************",__func__,__LINE__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
